export const getMinNum = (v, m) => {
  let minNum = m;
  let result = true;

  while (result) {
    result = v.some(d => d % minNum !== 0);
    minNum--;
  }

  return minNum + 1;
}

export default class Timer {
  length = 0;
  handlers = [];
  minTime = 1000;
  
  init() {
    if (this.length && this.length !== this.handlers.length) return;

    const setMinTime = (data) => {
      const arr = data.map(d => d.time);
      let minNum = arr.sort((a, b) => a - b)[0];
  
      minNum = getMinNum(arr, minNum);
  
      this.minTime = minNum * 1000;
    }
    
    let count = 1;
    setMinTime(this.handlers);
    
    this.timer = setInterval(() => {
      this.handlers.forEach(d => {
        let total = count * this.minTime / 1000;
        let result = total % d.time === 0;
        
        if (result) {
          d.handler(true);
        }
      });
      
      count++;
    }, this.minTime);
  }

  register(id, handler, time) {
    this.handlers.push({ id, handler, time });
  }

  setLength(length) {
    this.length = length;
  }

  clear(id) {
    clearInterval(this.timer);
    
    if (id) {
      const index = this.handlers.findIndex(d => id === d.id);

      this.handlers.splice(index, 1);
      this.length = this.handlers.length;
      this.init()
    } else {
      this.handlers = [];
    }
  }
}
